<?php


namespace app\pc\service\base;


use app\admin\model\base\Practise;
use app\admin\model\base\PractiseSubject;
use app\admin\model\base\StudentPractiseSubject;
use app\BaseService;
use think\response\Json;
use app\admin\model\base\StudentPractise;

class StudentPractiseService extends BaseService
{
    /**
     * 添加练习
     * @param array $params
     * @return Json
     */
    public function save(array $params): Json
    {
        if(!isset($params['practise_id'])) return jsonReturn(0, [],'非法操作');
        if(!intval($params['practise_id'])) return jsonReturn(0, [],'非法操作');
        //判断学生是否存在该试卷中
        $info = Practise::where('id','=',$params['practise_id'])->find();
        if(!$info) return jsonReturn(0, [],'练习不存在');
        //验证是否超时
        if(strtotime($info->start_time) > time()){
            return jsonReturn(0, [],'练习时间未到');
        }
        if(strtotime($info->end_time) < time()){
            return jsonReturn(0, [],'练习时间已结束');
        }
        $data = StudentPractise::create([
            'practise_id'=>$params['practise_id'],
            'student_id'=>PC_USER_ID,
            'start_time'=>date('Y-m-d H:i:s',time()),
        ]);
        //把考试题目创建进去
        $s = PractiseSubject::where('practise_id','=',$info->id)->select()->toArray();
        $id = $data->id;
        $addData = [];
        if(!empty($s)){
            foreach ($s as $value){
                $addData[] = [
                    'subject_id'=>$value['subject_id'],
                    'type'=>$value['type'],
                    'degree'=>$value['degree'],
                    'title'=>$value['title'],
                    'content'=>$value['content'],
                    'analysis'=>$value['analysis'],
                    'lable'=>$value['lable'],
                    'analysis_desc'=>$value['analysis_desc'],
                    'weighting'=>$value['weighting'],
                    'practise_id'=>$params['practise_id'],
                    'student_practise_id'=>$id,
                ];
            }
        }
        if(!empty($addData)){
            \think\facade\Db::name('student_practise_subject')->insertAll($addData);
        }
        if($data){
            return jsonReturn(1, ['id'=>$id]);
        }
        return jsonReturn(0, []);


        $data = StudentPractise::create([
            'practise_id'=>$params['practise_id'],
            'student_id'=>PC_USER_ID,
            'start_time'=>date('Y-m-d H:i:s',time()),
        ]);
        if($data){
            return jsonReturn(1, []);
        }
        return jsonReturn(0, []);
    }

    /**
     * 练习详情
     * @param array $params
     * @return Json
     */
    public function details(array $params): Json
    {
        $info = StudentPractise::where('id','=',$params['id'])
            ->with(['student_practise_subject'])
            ->find();
        if($info){
            $info = $info->toArray();
            if(!empty($info['student_practise_subject'])){
                foreach ($info['student_practise_subject'] as $k=>$item){
                    unset($info['student_practise_subject'][$k]['analysis']);
                    unset($info['student_practise_subject'][$k]['analysis_desc']);
                    $arr = json_decode($item['content'],true);
                    if($item['type'] == 1 || $item['type'] == 2){
                        if(isset($arr['list']) && !empty($arr['list'])){
                            foreach ($arr['list'] as $kk=>$value){
                                unset($arr['list'][$kk]['is_answer']);
                            }
                        }
                    }
                    $info['student_practise_subject'][$k]['content'] = $arr;
                }
            }
        }
        return jsonReturn(1, $info);
    }

    /**
     * 更新练习
     * @param array $params
     * @return Json
     */
    public function update(array $params): Json
    {
        $info = StudentPractise::where('id','=',$params['id'])->where('Student_id','=',PC_USER_ID)->find();
        if(!$info) return jsonReturn(0, [],'非法操作');
        //验证是否超时
        $infos = Practise::findOne(['id'=>$info->practise_id]);
        if(strtotime($infos['start_time']) > time()){
            return jsonReturn(0, [],'练习时间未到');
        }
        if(strtotime($infos['end_time']) < time()+300){
            return jsonReturn(0, [],'练习时间已结束');
        }
        if(!isset($params['list'])){
            return jsonReturn(0, [],'请选择要答题的题目');
        }
        $list = $params['list'];
        if(empty($list)){
            return jsonReturn(0, [],'未提交答案');
        }

        $data = [];
        $time = date('Y-m-d H:i:s',time());
        $subject_num = count($list);
        $subject_use_num = 0;
        foreach ($list as $value){
            $updateData = [
                'status'=>0,
                'student_analysis'=>'',
                'id'=>$value['id'],
            ];
            if(isset($value['student_analysis']) && $value['student_analysis']){
                $updateData['status'] =1;
                $updateData['student_analysis'] = $value['student_analysis'];
                $subject_use_num += 1;
            }
            $data[] = $updateData;
        }
        if(empty($data)){
            return jsonReturn(0, [],'未提交答案');
        }
        \think\facade\Db::startTrans();
        $StudentPaperSubject = new StudentPractiseSubject();
        try {
            $res = $StudentPaperSubject->saveAll($data);
            if(!$res){
                throw new \Exception('提交失败');
            }
            //更新用户交卷状态
            $take_time = (time() - strtotime($info->start_time)) / 60;
            $res = StudentPractise::where('id','=',$params['id'])
                ->update(['status'=>1,'end_time'=>$time,'take_time'=>$take_time]);
            if(!$res) throw new \Exception('更新失败');
            \think\facade\Db::commit();
            event('practise',['id'=>$params['id']]);
            //查询用户分数
            $score = StudentPractise::where('id','=',$params['id'])->value('score');
            return jsonReturn(1, ['time'=>$time,'task_time'=>$take_time,'subject_num'=>$subject_num,'subject_use_num'=>$subject_use_num,'score'=>$score],'交卷成功');
        }catch (\Exception $exception){
            \think\facade\Db::rollback();
            return jsonReturn(1, [],'交卷失败');
        }



        if($params['type'] == 1){
            //答题
            //获取题目
            $info = PractiseSubject::where('id','=',$params['practise_subject_id'])->find();
            if($info) $info = $info->toArray();
            $dataUpdate = [
                'title'=>$info['title'],
                'degree'=>$info['degree'],
                'practise_id'=>$info['practise_id'],
                'sort'=>$info['sort'],
//                        'create_user'=>WS_ADMIN_ID,
                'type'=>$info['type'],
                'subject_id'=>$info['subject_id'],
                'analysis'=>$info['analysis'],
                'analysis_desc'=>$info['analysis_desc'],
                'lable'=>$info['lable'],
                'student_analysis'=>$params['student_analysis'],
                'student_practise_id'=>$params['id'],
                'content'=>$info['content'],
            ];
            $infos = StudentPractiseSubject::where('student_practise_id','=',$params['id'])
                ->where('subject_id','=',$info['subject_id'])
                ->find();
            if($infos){
                //修改
                $res = StudentPractiseSubject::where('id','=',$infos->id)->update(['student_analysis'=>$params['student_analysis'],'status'=>1]);
            }else{
                //新增
                $res = StudentPractiseSubject::create($dataUpdate);
            }
        }else{
            //交卷
            $res = StudentPractise::where('id','=',$params['id'])->update(['status'=>1,'end_time'=>date('Y-m-d H:i:s',time())]);
        }
        if($res){
            if($params['type'] == 2){
                event('practise',['id'=>$params['id']]);
            }
            return jsonReturn(1, []);
        }
        return jsonReturn(0, [],'保存失败');
    }
}